#!/bin/bash

# 盲盒订单关联表迁移执行脚本
# 用途：自动执行 Phinx 迁移创建 sh_order_blind_box 表
# 使用方法: bash run_migration.sh

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目路径
PROJECT_DIR="/www/wwwroot/sm_shop-tp6/sm_shop_tp8"

echo "=========================================="
echo "盲盒订单关联表迁移工具"
echo "=========================================="
echo ""

# 检查项目目录
if [ ! -d "$PROJECT_DIR" ]; then
    echo -e "${RED}✗ 项目目录不存在: $PROJECT_DIR${NC}"
    exit 1
fi

cd "$PROJECT_DIR" || exit 1
echo -e "${GREEN}✓ 当前目录: $(pwd)${NC}"
echo ""

# 检查 think 命令
if [ ! -f "think" ]; then
    echo -e "${RED}✗ think 命令文件不存在${NC}"
    exit 1
fi

echo -e "${BLUE}步骤1: 查看当前迁移状态${NC}"
php think migrate:status
echo ""

echo -e "${YELLOW}步骤2: 执行迁移${NC}"
read -p "是否继续执行迁移? (y/n): " confirm

if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    echo -e "${RED}操作已取消${NC}"
    exit 0
fi

echo ""
echo -e "${YELLOW}正在执行迁移...${NC}"
php think migrate:run

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ 迁移执行成功${NC}"
else
    echo -e "${RED}✗ 迁移执行失败${NC}"
    exit 1
fi

echo ""
echo -e "${BLUE}步骤3: 验证迁移结果${NC}"
php think migrate:status
echo ""

echo -e "${BLUE}步骤4: 验证数据库表${NC}"
read -p "请输入数据库用户名 (默认: root): " DB_USER
DB_USER=${DB_USER:-root}

read -p "请输入数据库名称: " DB_NAME

if [ -z "$DB_NAME" ]; then
    echo -e "${YELLOW}⚠ 未输入数据库名称，跳过数据库验证${NC}"
else
    echo ""
    echo -e "${YELLOW}检查表是否存在...${NC}"
    mysql -u "$DB_USER" -p -D "$DB_NAME" -e "SHOW TABLES LIKE 'sh_order_blind_box';"
    
    echo ""
    echo -e "${YELLOW}显示表结构...${NC}"
    mysql -u "$DB_USER" -p -D "$DB_NAME" -e "DESC sh_order_blind_box;"
    
    echo ""
    echo -e "${YELLOW}显示索引...${NC}"
    mysql -u "$DB_USER" -p -D "$DB_NAME" -e "SHOW INDEX FROM sh_order_blind_box;"
fi

echo ""
echo -e "${GREEN}=========================================="
echo "迁移完成！"
echo "==========================================${NC}"
echo ""
echo "后续步骤:"
echo "1. 验证应用功能是否正常"
echo "2. 检查相关 API 接口"
echo "3. 查看文档: BLINDBOX_MIGRATION_GUIDE.md"
echo ""
echo "如需回滚，执行以下命令:"
echo "cd $PROJECT_DIR"
echo "php think migrate:rollback"
echo ""
